package com.vgooo.client.myvg;

import java.util.HashMap;
import java.util.Map;

import android.content.Context;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnKeyListener;
import android.view.ViewGroup.LayoutParams;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import com.umeng.analytics.MobclickAgent;
import com.vgooo.bean.UserInfo;
import com.vgooo.client.Main;
import com.vgooo.client.R;
import com.vgooo.client.VGActivity;
import com.vgooo.client.VGApplication;
import com.vgooo.client.ViewLayout;
import com.vgooo.client.myvg.OtherLogin.LoginListener;
import com.vgooo.client.myvg.tencent.QQOauthorizeAction;
import com.vgooo.client.myvg.weibo.WeiBoOauthorizeAction;
import com.vgooo.util.DebugTools;
import com.vgooo.util.GSonTools;
import com.vgooo.util.HttpUtils;
import com.vgooo.util.JsonParserUtils;
import com.vgooo.util.MD5Utils;
import com.vgooo.util.MatchUtils;
import com.vgooo.util.SimpleLoading;
import com.vgooo.util.SimpleLoading.Progress;
import com.vgooo.util.UmengUtils;
import com.vgooo.util.Utils;

public class MyLoginActivity extends VGActivity {

	private String className = "LoginActivity";

	private UserInfo userInfo;// 用户信息

	private EditText userName;// 用户名
	private EditText password;// 密码
	private TextView bind;
	private View weiBoLogin, qQLogin, otherLoginView;

	private boolean isBind = false;

	private int type;

	private String token;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
	}

	@Override
	public void addListener() {
		// TODO Auto-generated method stub
		OnKeyListener keyListener = new MyOnKeyClickListener();
		userName.setOnKeyListener(keyListener);
		password.setOnKeyListener(keyListener);
	}

	@Override
	protected void onResume() {
		// TODO Auto-generated method stub
		// 友盟统计功能，打开页面
		MobclickAgent.onResume(this);
		super.onResume();
		setContentView(R.layout.login);
		initView();
		addListener();
		setupView();
		// new QQOauthorizeAction(this, null, null);
	}

	@Override
	protected void onPause() {
		// TODO Auto-generated method stub
		super.onPause();
		// 友盟统计功能，页面关闭
		MobclickAgent.onPause(this);
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		// TODO Auto-generated method stub
		super.onActivityResult(requestCode, resultCode, data);
		if (null == data) {
			return;
		}
		Bundle bundle = data.getExtras();
		Map<String, Object> map = GSonTools.getObjectMaps(bundle
				.getString("key_response"));
		if (null == map || map.isEmpty()) {
			return;
		}
		final String openId = (String) map.get("openid");
		if (null != openId && !"".equalsIgnoreCase(openId)) {
			OtherLogin.OtherLogin(cparent, openId, OtherLogin.TYPE_QQ,
					new LoginListener() {

						@Override
						public void success(String info) {
							// TODO Auto-generated method stub
							Toast.makeText(context, "登录成功", Toast.LENGTH_SHORT)
									.show();
							ViewLayout.setViewBack();
						}

						@Override
						public void fail(String info, String token) {
							token = openId;
							// TODO Auto-generated method stub
							if (null != token && !"".equals(token.trim())
									&& token.length() > 10) {
								registerOrBind(OtherLogin.TYPE_QQ, token);
							} else {
								Toast.makeText(context, "登录失败",
										Toast.LENGTH_SHORT).show();
							}
						}
					});
		}

	}

	public void initView() {
		// TODO Auto-generated method stub
		bind = (TextView) findViewById(R.id.login_bind_text);
		userName = (EditText) findViewById(R.id.login_user_account);
		password = (EditText) findViewById(R.id.login_user_pwd);
		weiBoLogin = findViewById(R.id.login_weibo);
		qQLogin = findViewById(R.id.login_qq);
		otherLoginView = findViewById(R.id.login_more);

		// registerIntentReceivers();
	}

	public void setupView() {
		// TODO Auto-generated method stub
		if (userInfo != null && userInfo.user_id != null
				&& !"".equals(userInfo.user_id)) {
			userName.setText(userInfo.user_email);
			password.setText(userInfo.password);
		}

		setBindText();
	}

	@Override
	public void doClick(View v) {
		// TODO Auto-generated method stub
		super.doClick(v);
		switch (v.getId()) {
		case R.id.login_denglu:
			Utils.hideSoftInput(password);

			try {
				login(userName.getText().toString().trim(), password.getText()
						.toString().trim());
			} catch (Exception e) {
				e.printStackTrace();
				UmengUtils.onError(this, e.toString());
			}
			break;
		case R.id.login_weibo:
			new WeiBoOauthorizeAction(cparent, className, new LoginListener() {

				@Override
				public void success(String info) {
					Toast.makeText(context, "登录成功", Toast.LENGTH_SHORT).show();
					ViewLayout.setViewBack();
				}

				@Override
				public void fail(String info, String token) {
					// TODO Auto-generated method stub
					if (null != token && !"".equals(token.trim())
							&& token.length() > 10) {
						registerOrBind(OtherLogin.TYPE_WEI_BO, token);
					} else {
						Toast.makeText(context, "登录失败", Toast.LENGTH_SHORT)
								.show();
					}
				}
			});
			break;
		case R.id.login_qq:
			new QQOauthorizeAction(this, null, new LoginListener() {

				@Override
				public void success(String info) {
					// TODO Auto-generated method stub
					Toast.makeText(context, "登录成功", Toast.LENGTH_SHORT).show();
					ViewLayout.setViewBack();
				}

				@Override
				public void fail(String info, String token) {
					// TODO Auto-generated method stub
					if (null != token && !"".equals(token.trim())
							&& token.length() > 10) {
						registerOrBind(OtherLogin.TYPE_QQ, token);
					} else {
						Toast.makeText(context, "登录失败", Toast.LENGTH_SHORT)
								.show();
					}
				}
			});
			break;

		default:
			break;
		}
	}

	public void login(String name, String pwd) throws Exception {
		DebugTools.log(className, "name = " + name + " password = " + pwd);
		if (name == null || "".equals(name)) {
			userName.requestFocus();
			userName.setError("用户名不能为空！");
			return;
		}
		if (!MatchUtils.isEmail(name)) {
			userName.requestFocus();
			userName.setError("邮箱格式错误");
			return;
		}
		if (pwd == null || "".equals(pwd)) {
			password.requestFocus();
			password.setError("密码不能为空！");
			return;
		}
		if (pwd.length() < 6) {
			password.requestFocus();
			password.setError("密码长度大于6！");
			return;
		}

		if (isBind) {
			OtherLogin.BindLogin(cparent, name, pwd, token, type,
					new LoginListener() {

						@Override
						public void success(String info) {
							// TODO Auto-generated method stub
							Toast.makeText(Main.activity, "绑定成功！",
									Toast.LENGTH_SHORT).show();
							ViewLayout.setViewBack();
							isBind = false;
						}

						@Override
						public void fail(String info, String token) {
							// TODO Auto-generated method stub
							Toast.makeText(Main.activity, "绑定失败！",
									Toast.LENGTH_SHORT).show();
							isBind = false;
						}
					});
			return;
		}
		new LoginAsyncTask(SimpleLoading.startProgress(cparent), context, name,
				pwd).execute("");

	}

	private class LoginAsyncTask extends AsyncTask<String, String, String> {

		private Progress progressDialog;
		private Context context;
		private String name;
		private String pwd;
		private Map<String, Object> map;

		public LoginAsyncTask(Progress progressDialog, Context context,
				String name, String pwd) {
			super();
			this.progressDialog = progressDialog;
			this.context = context;
			this.name = name;
			this.pwd = pwd;
		}

		@Override
		protected String doInBackground(String... params) {
			// TODO Auto-generated method stub
			String result = "0";
			try {

				// String urlPath = HttpUtils.BASE_URI +
				// "login?username="+name+"&password="
				// +pwd+"&code="+MD5Utils.getLCode(name, pwd);
				// String jsonString = HttpUtils.getJsonString(urlPath);
				String urlPath = HttpUtils.BASE_URI + "login";// ?username="+name+"&password=" +pwd+"&code="+MD5Utils.getLCode(name,
																// pwd);
				Map<String, String> param = new HashMap<String, String>();
				param.put("username", name);
				param.put("password", pwd);
				param.put("code", MD5Utils.getLCode(name, pwd));
				String jsonString = HttpUtils.doPost(urlPath, param);
				userInfo = JsonParserUtils.getUserInfo(jsonString);
				userInfo.user_email = name;
				userInfo.password = pwd;
				userInfo.isLogin = true;
				VGApplication.userInfo = userInfo;
				// 保存用户信息
				UserUtils.writeUserInfo(userInfo, context);
				DebugTools.log(className, "jsonString = " + jsonString);
				map = GSonTools.getObjectMaps(jsonString);
				result = jsonString;

			} catch (Exception e) {
				// TODO: handle exception
				e.printStackTrace();
				return null;
			}
			return result;
		}

		@Override
		protected void onPostExecute(String result) {
			// TODO Auto-generated method stub

			if (null == userInfo || !userInfo.isLogin) {
				Toast.makeText(context, "用户名或密码错误！", Toast.LENGTH_SHORT).show();
			} else {
				Utils.hideSoftInput(password);
				Toast.makeText(context, "登录成功!", Toast.LENGTH_SHORT).show();
				ViewLayout.setViewBack();
			}
			progressDialog.cancel();

			super.onPostExecute(result);
		}

		@Override
		protected void onProgressUpdate(String... values) {
			// TODO Auto-generated method stub
			super.onProgressUpdate(values);
		}

	}

	private class MyOnKeyClickListener implements OnKeyListener {

		@Override
		public boolean onKey(View v, int keyCode, KeyEvent event) {
			if (keyCode == KeyEvent.KEYCODE_ENTER) {
				// DebugTools.toast(context, "KEYCODE_ENTER") ;
				try {
					login(userName.getText().toString().trim(), password
							.getText().toString().trim());
				} catch (Exception e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
					UmengUtils.onError(context, e.toString());
				}
			}
			return false;
		}

	}

	/**
	 * 注册或绑定
	 * 
	 * @param type
	 * @param token
	 */
	private void registerOrBind(final int type, final String token) {
		this.token = token;
		this.type = type;
		final View view = inflater.inflate(R.layout.bind_or_register, null);
		// 注册
		view.findViewById(R.id.bind_or_register_register).setOnClickListener(
				new OnClickListener() {

					@Override
					public void onClick(View v) {
						// TODO Auto-generated method stub
						Main.registerIntent.putExtra("token", token);
						Main.registerIntent.putExtra("type", type);
						ViewLayout.setViewPre(true, "完善资料",
								ViewLayout.TAB_TAG_REGISTER, cparent);
						view.setVisibility(View.GONE);
					}
				});
		// 绑定
		view.findViewById(R.id.bind_or_register_bind).setOnClickListener(
				new OnClickListener() {

					@Override
					public void onClick(View v) {
						// TODO Auto-generated method stub
						isBind = true;
						view.setVisibility(View.GONE);
						setBindText();
						Utils.showSoftInput(userName);
					}
				});
		addContentView(view, new LayoutParams(LayoutParams.FILL_PARENT,
				LayoutParams.FILL_PARENT));

	}

	private void setBindText() {
		if (null == bind) {
			return;
		}
		if (isBind) {
			otherLoginView.setVisibility(View.GONE);
			bind.setText("关联账号？");
		} else {
			otherLoginView.setVisibility(View.VISIBLE);
			bind.setText("使用VGOOO账号登录");
		}
	}

}
